package com.lamb.script.core.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * http 请求功能.
 *
 * @author : lamb
 * @version : 1.0
 * @date :  2019-08-08 10:12
 **/
public class HttpUtil {

    /**
     * chrome 隐藏身份.
     */
    private static final String USER_AGENT_CHROME = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 " +
            "(KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36";

    /**
     * get 请求.
     *
     * @param urlString 地址.
     * @return 数据.
     * @throws IOException 异常.
     */
    public static byte[] httpGet(String urlString) throws IOException {
        InputStream in = null;
        try {
            URL url = new URL(urlString);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Connection", "Closed");
            conn.setRequestProperty("User-Agent", USER_AGENT_CHROME);
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(60000);
            conn.connect();
            if (conn.getResponseCode() == 302 || conn.getResponseCode() == 301) {
                return httpGet(conn.getHeaderField("Location"));
            }
            //获取URLConnection对象对应的输入流
            in = conn.getInputStream();
            String contentLength = conn.getHeaderField("Content-Length");
            if (null != contentLength) {
                return ScriptUtil.readToByteBufferByLength(in, Integer.valueOf(contentLength));
            }
            return ScriptUtil.readToByteBuffer(in);
        } finally {
            ScriptUtil.closeQuietly(in);
        }
    }
}
